from datetime import datetime
from app import db


class Role(db.Model):
    """角色模型"""
    __tablename__ = 'role'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, comment='角色名称')
    key = db.Column(db.String(100), unique=True, comment='权限字符')
    description = db.Column(db.Text, comment='角色描述')
    data_scope = db.Column(db.String(20), default='dept', comment='数据权限范围')
    status = db.Column(db.Boolean, default=True, comment='状态(True=启用,False=禁用)')
    sort = db.Column(db.Integer, default=0, comment='排序')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 数据权限范围常量
    DATA_SCOPE_ALL = 'all'           # 全部数据权限
    DATA_SCOPE_CUSTOM = 'custom'     # 自定数据权限
    DATA_SCOPE_DEPT = 'dept'         # 部门数据权限
    DATA_SCOPE_DEPT_AND_CHILD = 'dept_and_child'  # 部门及以下数据权限
    DATA_SCOPE_SELF = 'self'         # 个人数据权限
    
    # 多对多关系
    menus = db.relationship('Menu', secondary='role_menu', backref='roles')
    
    @classmethod
    def get_data_scope_choices(cls):
        """获取数据权限选项"""
        return [
            {'value': cls.DATA_SCOPE_ALL, 'label': '全部数据权限'},
            {'value': cls.DATA_SCOPE_CUSTOM, 'label': '自定数据权限'},
            {'value': cls.DATA_SCOPE_DEPT, 'label': '部门数据权限'},
            {'value': cls.DATA_SCOPE_DEPT_AND_CHILD, 'label': '部门及以下数据权限'},
            {'value': cls.DATA_SCOPE_SELF, 'label': '个人数据权限'},
        ]
    
    def get_data_scope_label(self):
        """获取数据权限范围标签"""
        choices = self.get_data_scope_choices()
        for choice in choices:
            if choice['value'] == self.data_scope:
                return choice['label']
        return '未知权限'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'key': self.key,
            'description': self.description,
            'data_scope': self.data_scope,
            'data_scope_label': self.get_data_scope_label(),
            'status': self.status,
            'sort': self.sort,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }


class RoleMenu(db.Model):
    """角色菜单关联表"""
    __tablename__ = 'role_menu'
    
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), primary_key=True)
    menu_id = db.Column(db.Integer, db.ForeignKey('menu.id'), primary_key=True)


class RolePermission(db.Model):
    """角色按钮权限表"""
    __tablename__ = 'role_permission'
    
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False)
    menu_id = db.Column(db.Integer, db.ForeignKey('menu.id'), nullable=False)
    permission = db.Column(db.String(50), nullable=False, comment='权限标识')
    
    # 关联关系
    role = db.relationship('Role', backref='permissions')
    menu = db.relationship('Menu', backref='permissions') 